import { FC, useCallback } from 'react';
import { Popover, List } from 'antd';
import { observer, useLocalStore } from 'mobx-react';
import * as AntdIcons from '@ant-design/icons';

import Button from '@components/Button';
import Icons from '@components/Icons';

import styles from './index.module.less';
import { icons } from './icons';

export type IconListProps = {
  /** Antd中图标的类型 */
  value?: keyof typeof AntdIcons;

  /** 选中图标后触发事件 返回图标类型字符串 */
  onChange?: (value: keyof typeof AntdIcons) => void;
};

const IconList: FC<IconListProps> = ({ value, onChange, ...rest }) => {
  const store = useLocalStore(() => ({
    openFlag: false,
    iconType: ''
  }));

  /** 返回修改 */
  const triggerChange = useCallback(
    (changedValue: any) => {
      onChange?.(changedValue || value || store.iconType);
    },
    [onChange, value]
  );

  /** 选择图标 */
  const choiceIcon = useCallback(
    (iconType: string) => {
      store.iconType = iconType;
      triggerChange(iconType);
      store.openFlag = false;
    },
    [triggerChange]
  );

  // @ts-ignore
  /** 渲染图标列表 */
  const content = (
    <>
      <List
        className={styles.rbIconList}
        grid={{ column: 6 }} // 每行列数
        dataSource={icons}
        renderItem={(item: any) => {
          return (
            item.type && (
              <List.Item>
                <div className={styles.rbIconListItem}>
                  <Button
                    shape="circle"
                    icon={<Icons type={item.type} onClick={() => choiceIcon(item.type)} />}
                  />
                </div>
              </List.Item>
            )
          );
        }}
        pagination={{
          // @ts-ignore
          size: 12, // 每页大小
          simple: true
        }}
      />
    </>
  );

  return (
    <Popover
      trigger="click"
      placement="bottom"
      content={content}
      open={store.openFlag}
      onOpenChange={(newOpenFlag: boolean) => (store.openFlag = newOpenFlag)}
    >
      <Button shape="circle" icon={<Icons type={value || 'DropboxOutlined'} />} {...rest} />
    </Popover>
  );
};

export default observer(IconList);
